package com.sm.li.common.exception;

import com.sm.li.common.http.AxiosResult;
import com.sm.li.common.http.AxiosStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    //处理表单校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AxiosResult<String> handlerFormValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        AxiosStatus formValidError = AxiosStatus.FORM_VALID_ERROR;
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        if (!CollectionUtils.isEmpty(fieldErrors)){
            FieldError fieldError = fieldErrors.get(0);
            String defaultMessage = fieldError.getDefaultMessage();
            formValidError.setMessage(defaultMessage);
            return AxiosResult.error(formValidError);
        }
        formValidError.setMessage("表单校验错误");
        return AxiosResult.error(formValidError);

    }
    //处理表单校验异常
    @ExceptionHandler(ApiException.class)
    public AxiosResult<Void> ApiException(ApiException e) {
        return AxiosResult.error(e.getAxiosStatus());

    }
    //处理表单校验异常
    @ExceptionHandler(Throwable.class)
    public AxiosResult<Void> handlerThrowable(Throwable e) {
        AxiosStatus unknownError = AxiosStatus.UNKNOWN_ERROR;
        unknownError.setMessage(e.getMessage());
        return AxiosResult.error(unknownError);

    }
      //处理手动表单校验异常
    @ExceptionHandler(FormValidException.class)
    public AxiosResult<Map<String,String>> handlerFormValidException(FormValidException e) {
        AxiosStatus axiosStatus = e.getAxiosStatus();
        return AxiosResult.error(axiosStatus,e.getMap());

    }

}
